﻿using System;
using Taobao.ObjectModel.Request;

namespace Jlvier.TaobaoShowcase.Service
{
    public class ProductItemsRetriever
    {
        public event EventHandler<ProductsRetrievedEventArgs> OnProductsRetrieved;

        private readonly IProductItemsRequestWrapper request;
        private readonly Predicate<Response> predicate;

        public ProductItemsRetriever(IProductItemsRequestWrapper request)
            :this(request,DefaultPredicate)
        {
            
        }
        public ProductItemsRetriever(IProductItemsRequestWrapper request,Predicate<Response> predicate)
        {
            this.request = request;
            this.predicate = predicate;
        }


        public void Fetch()
        {
            while (true)
            {
                var response = request.GetResponse();
                RaiseRetrieved(response);
                if (predicate(response)) break;
                request.MoveNext();
            }
        }
        private void RaiseRetrieved(Response response)
        {
            if (null != OnProductsRetrieved)
            {
                foreach (var item in response.Result)
                {
                    OnProductsRetrieved(this, new ProductsRetrievedEventArgs(item));
                }
            }
        }

        private static bool DefaultPredicate(Response response)
        {
            return response.Count >= response.TotalCount;
        }
    }
}